from django.utils import simplejson
from socialbar.constants import DEALSSTATUS, keyFromValue
from socialbar.models import Bar, Greeting, Deal
from socialbar import paiementControl
import logging
import urllib

def getData(request, params):
  data = {}
  
  if 'trxId' in request.GET:
    data['verifyTrxMsg'] = paiementControl.verifyTrx(request)
    
  if 'all' in params or 'dealBoughtCount' in params:
    if request.user.is_authenticated():
      dealsBought = Deal.objects.filter(user=request.user,
          status=keyFromValue(DEALSSTATUS, 'Bought'))
      data['dealBoughtCount'] = str(len(dealsBought))

  if 'all' in params or 'dealsUsedCurrentBarCount' in params:
    if request.user.is_authenticated():
      dealsUsedCurrentBar = Deal.objects.filter(user=request.user,
          status=keyFromValue(DEALSSTATUS, 'Used'),
          bar = getBar(getCurrentBar(request)))
      data['dealsUsedCurrentBarCount'] = str(len(dealsUsedCurrentBar))


  
  return simplejson.dumps(data)


def getCurrentBar(request):
  if request.session.has_key('currentBar'):
    return request.session['currentBar']
  else:
    logging.debug('Functional error : No Bar set in session')
    return None
  
def getBar(barName):
  barName = urllib.unquote_plus(barName)
  logging.debug('DEBUG = =  = = = = = = = = =  =' + barName)
  bars = Bar.objects.filter(name=barName)
  return bars[0]